package cn.itcast.itcaststore.dao.Impl;

import cn.itcast.itcaststore.dao.OrderDao;
import cn.itcast.itcaststore.domain.Orderitem;
import cn.itcast.itcaststore.domain.Orders;
import cn.itcast.itcaststore.domain.Products;
import cn.itcast.itcaststore.utils.JDBCUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

public class IOderDao implements OrderDao {

    private JdbcTemplate jdbcTemplate = new JdbcTemplate(JDBCUtils.getDataSource());

    @Override
    public void create(Orders orders) {
        String sql = "insert into orders values(?,?,?,?,?,?,?,?)";
        jdbcTemplate.update(sql,orders.getId(),orders.getMoney(),
                orders.getReceiverAddress(),
                orders.getReceiverName(),
                orders.getReceiverPhone(),
                orders.getPaystate(),
                orders.getOrdertime(),
                orders.getUser_id()
                );

    }

    @Override
    public Orders getOrders(String type, Long by) {
        String sql = "select*from orders where "+type+"=?";
        List<Orders> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<Orders>(Orders.class), by);
        Orders orders=null;
        for (Orders o : list) {
            orders=o;
        }
        return orders;
    }

    @Override
    public List<Orderitem> getOrderitem(long id) {
        String sql = "select*from orderitem where order_id=?";
        List list = jdbcTemplate.query(sql,new BeanPropertyRowMapper<Orderitem>(Orderitem.class),id);
        return list;
    }

    @Override
    public Products getProducts(String product_id) {
        String sql = "select*from products where id=?";
        List<Products> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<Products>(Products.class), product_id);

        Products p=null;

        for (Products products : list) {
            p=products;
        }
        return p;
    }

    @Override
    public void upatePay(String order_id) {
        String sql = "update orders set paystate=1 where id=?";
        jdbcTemplate.update(sql,order_id);
    }

    @Override
    public List getList(String username) {
        String sql = "select*from orders where receiverName=?";
        List<Orders> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<Orders>(Orders.class), username);
        return list;
    }

    @Override
    public void delById(String id) {
        String sql = "delete from orders where id=?";
        jdbcTemplate.update(sql,id );
    }
}
